﻿using AutoMapper;
using Model.Entitys;
using Model.Other;
using Shop.Interface.Repository;
using Shop.Interface.Role;
using Shop.Models.Dto.Role;
using Shop.Services.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Shop.Services
{
    public class RoleService : IRoleService
    {
        private readonly IBaseRepository _repository;
        private readonly IMapper _mapper;

        public RoleService(IBaseRepository repository, IMapper mapper)
        {
            _repository=repository;
            _mapper=mapper;
        }
        public async Task<bool> Add(RoleAdd req, string userId)
        {
            Role info=_mapper.Map<Role>(req);
            info.Id=Guid.NewGuid().ToString();
            info.CreateDate=DateTime.Now;
            info.CreateUserId=userId;
            info.IsDeleted=false;
            return await _repository.CreateAsync(info);
        }

        public async Task<bool> BatchDel(string[] ids)
        {
            return await _repository.BatchDelete<Role>(ids);
        }

        public async Task<bool> Del(string id)
        {
            return await _repository.DeleteById<Role>(id);
        }

        public async Task<bool> Edit(RoleEdit req, string userId)
        {
            var info = _repository.Querry<Role>(p=>p.Id==req.Id).FirstOrDefault();
            _mapper.Map(req,info);
            info.ModifyDate=DateTime.Now;
            info.ModifyUserId=userId;
            return await _repository.Db.Updateable<Role>(info).ExecuteCommandAsync()>0;
        }

        public async Task<PageInfo<RoleRes>> GetRoles(RoleReq req, string userId)
        {
            PageInfo<RoleRes> res= new PageInfo<RoleRes>();
            int total = 0;
            var list = await _repository.Db.Queryable<Role>()
                .LeftJoin<Users>((r, ul) => r.CreateUserId == ul.Id)
                .LeftJoin<Users>((r, ul, u2) => r.ModifyUserId == u2.Id)
                .WhereIF(!string.IsNullOrEmpty(req.Name), u => u.Name.Contains(req.Name))
                .WhereIF(!string.IsNullOrEmpty(req.Description), u => u.Description.Contains(req.Description))
                .OrderBy((r) => r.Order)
                .Select((r, ul, u2) => new RoleRes()
                {
                    Name = r.Name,
                    CreateUserName = ul.Name,
                    ModifyUserName = u2.Name,
                },true)
                .ToOffsetPageAsync(req.PageIndex,req.PageSize,total);
            res.Data = list;
            res.Total = total;
            return res;
        }
    }
}
